package com.property.demo.service.impl;

import com.property.demo.model.Building;
import com.property.demo.model.Home;
import com.property.demo.model.Owner;
import com.property.demo.repository.BuildingRepository;
import com.property.demo.repository.HomeRepository;
import com.property.demo.repository.OwnerRepository;
import com.property.demo.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private HomeRepository homeRepository;
    
    @Autowired
    private BuildingRepository buildingRepository;
    
    @Autowired
    private OwnerRepository ownerRepository;
    
    @Override
    public List<Home> findAll() {
        return homeRepository.findAll();
    }
    
    @Override
    public Page<Home> findAll(Pageable pageable) {
        return homeRepository.findAll(pageable);
    }
    
    @Override
    public Page<Home> findByFilters(Long buildingId, Long ownerId, String name, String status, Pageable pageable) {
        Specification<Home> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (buildingId != null) {
                predicates.add(criteriaBuilder.equal(root.get("building").get("id"), buildingId));
            }
            
            if (ownerId != null) {
                predicates.add(criteriaBuilder.equal(root.get("owner").get("id"), ownerId));
            }
            
            if (name != null && !name.isEmpty()) {
                predicates.add(criteriaBuilder.like(criteriaBuilder.lower(root.get("name")), "%" + name.toLowerCase() + "%"));
            }
            
            if (status != null && !status.isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("status"), status));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        return homeRepository.findAll(spec, pageable);
    }
    
    @Override
    public Optional<Home> findById(Long id) {
        return homeRepository.findById(id);
    }
    
    @Override
    public Home save(Home home) {
        // 验证楼栋是否存在
        if (home.getBuilding() != null && home.getBuilding().getId() != null) {
            Optional<Building> building = buildingRepository.findById(home.getBuilding().getId());
            if (!building.isPresent()) {
                throw new EntityNotFoundException("指定的楼栋不存在");
            }
            home.setBuilding(building.get());
        }
        
        // 验证业主是否存在
        if (home.getOwner() != null && home.getOwner().getId() != null) {
            Optional<Owner> owner = ownerRepository.findById(home.getOwner().getId());
            if (!owner.isPresent()) {
                throw new EntityNotFoundException("指定的业主不存在");
            }
            home.setOwner(owner.get());
        }
        
        return homeRepository.save(home);
    }
    
    @Override
    public Home update(Long id, Home homeDetails) {
        Optional<Home> homeOpt = homeRepository.findById(id);
        if (!homeOpt.isPresent()) {
            throw new EntityNotFoundException("房产不存在，ID: " + id);
        }
        
        Home existingHome = homeOpt.get();
        
        // 验证楼栋是否存在
        if (homeDetails.getBuilding() != null && homeDetails.getBuilding().getId() != null) {
            Optional<Building> building = buildingRepository.findById(homeDetails.getBuilding().getId());
            if (!building.isPresent()) {
                throw new EntityNotFoundException("指定的楼栋不存在");
            }
            existingHome.setBuilding(building.get());
        }
        
        // 验证业主是否存在
        if (homeDetails.getOwner() != null && homeDetails.getOwner().getId() != null) {
            Optional<Owner> owner = ownerRepository.findById(homeDetails.getOwner().getId());
            if (!owner.isPresent()) {
                throw new EntityNotFoundException("指定的业主不存在");
            }
            existingHome.setOwner(owner.get());
        }
        
        existingHome.setName(homeDetails.getName());
        existingHome.setFloor(homeDetails.getFloor());
        existingHome.setArea(homeDetails.getArea());
        existingHome.setType(homeDetails.getType());
        existingHome.setStatus(homeDetails.getStatus());
        
        return homeRepository.save(existingHome);
    }
    
    @Override
    public void delete(Long id) {
        if (!homeRepository.existsById(id)) {
            throw new EntityNotFoundException("房产不存在，ID: " + id);
        }
        homeRepository.deleteById(id);
    }
    
    @Override
    public void deleteAll(List<Long> ids) {
        homeRepository.deleteAllById(ids);
    }
    
    @Override
    public List<Home> findByBuildingId(Long buildingId) {
        return homeRepository.findByBuildingId(buildingId);
    }
    
    @Override
    public List<Home> findByOwnerId(Long ownerId) {
        return homeRepository.findByOwnerId(ownerId);
    }
    
    @Override
    public List<Home> findByNameContaining(String name) {
        return homeRepository.findByNameContaining(name);
    }
    
    @Override
    public List<Home> findByStatus(String status) {
        return homeRepository.findByStatus(status);
    }
} 